package dk.kapetanovic.jaft.log;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import dk.kapetanovic.jaft.action.Action;
import dk.kapetanovic.jaft.exception.InconsistentStateException;

public class JournalImpl implements Journal {
	
	private List<Action> actions = new
		ArrayList<Action>();
	
	public JournalImpl(List<Action> actions) {
		this.actions = actions;
	}
	
	public JournalImpl() {}

	@Override
	public void addAction(Action action) {
		actions.add(action);
	}
	
	@Override
	public List<Action> commit() {
		return actions;
	}
	
	@Override
	public void close() {}

	@Override
	public Action undo() throws InconsistentStateException {
		try {
			Action action = actions.remove(actions.size() - 1);
			action.undo();
			return action;
		}
		catch(IOException e) {
			throw new InconsistentStateException(e);
		}
	}

	@Override
	public int size() {
		return actions.size();
	}
}
